
package com.lzx.adx.report.controller.v1.wifi;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.lzs.adx.commmon.utils.JsonUtils;
import com.lzs.adx.commmon.utils.Result;
import com.lzx.adx.report.bean.mapper.ReportMapper;
import com.lzx.adx.report.cache.AccountLocalCache;
import com.lzx.adx.report.dto.AccountDTO;
import com.lzx.adx.report.dto.ReportDTO;
import com.lzx.adx.report.enums.CZCovertXMWifiEventTypeEnums;
import com.lzx.adx.report.enums.CzCovertWifiEventTypeEnums;
import com.lzx.adx.report.enums.ElmCovertWifiEventTypeEnums;
import com.lzx.adx.report.model.wifi.WifiRequest;
import com.lzx.adx.report.service.ReportService;
import com.lzx.adx.report.util.AdPerUtil;
import com.lzx.adx.report.util.UrlUtil;
import com.lzx.adx.report.util.helper.KkHeper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 美图广告上报
 */
@RequestMapping("/wifi/cz")
@RestController
@Slf4j
@RequiredArgsConstructor
public class WifiCzReportController {


    @Autowired
    private  ReportService reportService;

    @Autowired
    private  ThreadPoolTaskExecutor reportExecutor;

    @Autowired
    private  ReportMapper reportMapper;

    public static final   String apiDesc="wifi-cz";




    @GetMapping("/report")
    public ResponseEntity report(WifiRequest wifiRequest, HttpServletRequest request){
        AccountDTO accountDTO = AccountLocalCache.getInstance().get(wifiRequest.getDspId());
        log.info("接收到{}的请求参数为{}",accountDTO.getName(), JsonUtils.toJsonString(wifiRequest));
       //1.收到监测的数据存储
        ReportDTO reportDTO=reportMapper.toReportDTO(wifiRequest);
        reportDTO.setBizRequestId(IdUtil.fastSimpleUUID()+reportDTO.getDspId());
        reportDTO.setCreateTime(new Date());
        reportDTO.setUpdateTime(new Date());
        reportDTO.setExtend(JsonUtils.toJsonString(wifiRequest));
        reportDTO.setTraceTime(String.valueOf(System.currentTimeMillis()/1000));
        reportExecutor.execute(()->{
            reportService.saveData(reportDTO);
        });
        String finalUrl= KkHeper.covertChuangZhiUrl(accountDTO,wifiRequest,reportDTO);
        log.info("账号为{} 完整的{}请求地址为{}",wifiRequest.getDspId(),accountDTO.getName(),finalUrl);
        //2.2调用饿了嘛，上报接口
        String body = HttpUtil.createGet(finalUrl).execute().body();
        log.info("账号为{}完整的{}上报的接口,响应的结果为{}",wifiRequest.getDspId(),accountDTO.getName(),body);
        return ResponseEntity.ok(new Result());
    }


    /**
     * wifi - 创智关注注册和次留
     * @param requestId 请求参数
     * @return ResponseEntity
     * @throws Exception
     */
    @GetMapping("callback")
    public ResponseEntity callBackUrl(String requestId, String tnaEvent) throws Exception {
        log.info("wifi接收了创智回调信息 请求流水号{} 事件{}", requestId, tnaEvent);

        if(StringUtils.isBlank(tnaEvent)){
            tnaEvent="register";
        }

        String convType = "2";
        if (StringUtils.isNotBlank(tnaEvent)) {
            convType = CZCovertXMWifiEventTypeEnums.getWifiCode(tnaEvent);
            if (StringUtils.isBlank(convType)) {
                log.info("事件有误,wifi接收了创智回调信息 请求流水号{} 事件{}", requestId, tnaEvent);
                return ResponseEntity.ok(new Result());
            }
        }
        //1.把转换结果更新到数据库
        Map<String,Object> params=new HashMap<>();
        params.put("bizRequestId",requestId);
        List<ReportDTO> list = reportService.list(params);
        ReportDTO reportDTO;
        if(CollectionUtil.isNotEmpty(list)){
            reportDTO = list.get(0);
            reportDTO.setResultType(tnaEvent);
            reportDTO.setResultTime(String.valueOf(System.currentTimeMillis()));
            reportDTO.setUpdateTime(new Date());
            reportService.updateData(reportDTO,tnaEvent);
        }else{
            log.error("当前流水号，系统当前不存在");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }


        //2.从缓存加载配置
        AccountDTO accountDTO = AccountLocalCache.getInstance().get(reportDTO.getDspId());
        String sspExtend = accountDTO.getSspExtend();
        //如果不为空，且sspExtend
        if(StringUtils.isNotBlank(sspExtend)){
            JSONObject jsonObject = JSONObject.parseObject(sspExtend);
            Double per = jsonObject.getDouble("per");
            if(Objects.nonNull(per)){
                if(!AdPerUtil.randomPer(per)){
                    log.info("流水号为 {} 超出了比例外，本次随机的值为{}，dspId为{}",reportDTO.getBizRequestId(),per,reportDTO.getDspId());
                    return ResponseEntity.ok(new Result());
                }
            }
        }

        JSONObject jsonObject = JSONObject.parseObject(accountDTO.getSspExtend());
        String clientId = jsonObject.getString("clientid");
        log.info("elm-wifi,clienid{}",clientId);

        WifiRequest wifiRequest=JsonUtils.parseObject(reportDTO.getExtend(),WifiRequest.class);

        Map<String,Object> paramsReq=new HashMap<>();

        paramsReq.put("cid",wifiRequest.getContentId());
        paramsReq.put("sid",wifiRequest.getSid());
        paramsReq.put("stime",wifiRequest.getStime());
        paramsReq.put("os",wifiRequest.getOs());
        paramsReq.put("idfa",wifiRequest.getIdfaMd5());
        paramsReq.put("mac",wifiRequest.getMacMd5());
        paramsReq.put("imei",wifiRequest.getImeiMd5());
        paramsReq.put("clientid",clientId);
        paramsReq.put("ts",System.currentTimeMillis()/1000);
        paramsReq.put("event_type", convType);


        //将参数转换 进行排序转换为url
        String urlParams = UrlUtil.covertParamsOrderByAsc(paramsReq);
        String finalResultUrl=accountDTO.getSspApiUrl()+"?"+urlParams;

        String sign=StringUtils.upperCase(SecureUtil.md5(finalResultUrl+accountDTO.getSspKey()));
        String resultUrl = UrlUtil.handMeitu(finalResultUrl, sign);

         log.info("创智给wifi上报回传结果，完整的地址：{}",resultUrl);
         HttpRequest body = HttpUtil.createGet(resultUrl);
         String result = body.execute().body();
         log.info("dsp账户ID{}，接收wifi创智转换响应的结果为 {}",accountDTO.getId(),result);

         return ResponseEntity.ok(new Result());
   }



    /**
     * wifi - 创智关注注册和次留
     * @param requestId 请求参数
     * @return ResponseEntity
     * @throws Exception
     */
    @GetMapping("/dt/callback")
    public ResponseEntity dtCallBackUrl(String requestId, String tnaEvent) throws Exception {
        log.info("wifi接收了创智(点淘)回调信息 请求流水号{} 事件{}", requestId, tnaEvent);
        if (StringUtils.isBlank(requestId)) {
            log.info("wifi接收了创智(点淘)回调信息 请求流水号{} 事件{}", requestId, tnaEvent);
            return ResponseEntity.ok(new Result());
        }
        String eventType = "1";
        if(StringUtils.isBlank(tnaEvent)){
            tnaEvent=eventType;
        }

        //1.把转换结果更新到数据库
        Map<String, Object> params = new HashMap<>();
        params.put("bizRequestId", requestId);
        List<ReportDTO> list = reportService.list(params);
        ReportDTO reportDTO;
        if (CollectionUtil.isNotEmpty(list)) {
            reportDTO = list.get(0);
            reportDTO.setResultType(tnaEvent);
            reportDTO.setResultTime(String.valueOf(System.currentTimeMillis()));
            reportDTO.setUpdateTime(new Date());
            reportService.updateData(reportDTO,tnaEvent);
        } else {
            log.error("当前流水号，系统当前不存在");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        //2.从缓存加载配置
        AccountDTO accountDTO = AccountLocalCache.getInstance().get(reportDTO.getDspId());
        JSONObject jsonObject = JSONObject.parseObject(accountDTO.getSspExtend());
        String clientId = jsonObject.getString("clientid");
        WifiRequest wifiRequest = JsonUtils.parseObject(reportDTO.getExtend(), WifiRequest.class);
        Map<String, Object> paramsReq = new HashMap<>();
        paramsReq.put("cid", wifiRequest.getContentId());
        paramsReq.put("sid", wifiRequest.getSid());
        paramsReq.put("stime", wifiRequest.getStime());
        paramsReq.put("os", wifiRequest.getOs());
        paramsReq.put("idfa", wifiRequest.getIdfaMd5());
        paramsReq.put("mac", wifiRequest.getMacMd5());
        paramsReq.put("imei", wifiRequest.getImeiMd5());
        paramsReq.put("clientid", clientId);
        paramsReq.put("ts", System.currentTimeMillis() / 1000);
        paramsReq.put("event_type", eventType);
        //将参数转换 进行排序转换为url
        String urlParams = UrlUtil.covertParamsOrderByAsc(paramsReq);
        String finalResultUrl = accountDTO.getSspApiUrl() + "?" + urlParams;
        String sign = StringUtils.upperCase(SecureUtil.md5(finalResultUrl + accountDTO.getSspKey()));
        String resultUrl = UrlUtil.handMeitu(finalResultUrl, sign);
        log.info("账号{} 流水号{}创智(点淘) clientId:{}给wifi上报回传结果，完整的地址：{}", reportDTO.getDspId(),requestId,
                clientId,resultUrl);
        HttpRequest body = HttpUtil.createGet(resultUrl);
        String result = body.execute().body();
        log.info("账号{} 流水号{}创智(点淘) clientId:{}给wifi上报回传结果，响应的结果为{}", reportDTO.getDspId(),requestId,
                clientId,result);
        return ResponseEntity.ok(new Result());
    }











    /**
     * wifi - 创智关注注册和次留
     * @param requestId 请求参数
     * @return ResponseEntity
     * @throws Exception
     */
    @GetMapping("/rl/dt/callback")
    public ResponseEntity rlDtCallBackUrl(String requestId, String tnaEvent) throws Exception {
        log.info("wifi接收了创智如来(点淘)回调信息 请求流水号{} 事件{}", requestId, tnaEvent);
        if (StringUtils.isBlank(requestId)) {
            log.info("wifi接收了创智如来(点淘)回调信息 请求流水号{} 事件{}", requestId, tnaEvent);
            return ResponseEntity.ok(new Result());
        }
        String event = "default";
        if (StringUtils.isNotBlank(tnaEvent)) {
            event = tnaEvent;
        }
        //1.把转换结果更新到数据库
        Map<String, Object> params = new HashMap<>();
        params.put("bizRequestId", requestId);
        List<ReportDTO> list = reportService.list(params);
        ReportDTO reportDTO;
        if (CollectionUtil.isNotEmpty(list)) {
            reportDTO = list.get(0);
        } else {
            log.error("当前流水号，系统当前不存在");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        //2.从缓存加载配置
        AccountDTO accountDTO = AccountLocalCache.getInstance().get(reportDTO.getDspId());
        JSONObject jsonObject = JSONObject.parseObject(accountDTO.getSspExtend());
        String transformType = jsonObject.getString(event);
        if (StringUtils.isBlank(transformType)) {
            log.info("wifi接收了创智如来(点淘)的回调信息当前流水号：{}，事件类型{}不合法，不做数据回传", requestId, tnaEvent);
            return ResponseEntity.ok(new Result());
        }
        reportDTO.setResultType("1");
        reportDTO.setResultTime(String.valueOf(System.currentTimeMillis()));
        reportDTO.setUpdateTime(new Date());
        reportService.updateData(reportDTO,tnaEvent);
        String clientId = jsonObject.getString("clientid");
        WifiRequest wifiRequest = JsonUtils.parseObject(reportDTO.getExtend(), WifiRequest.class);
        Map<String, Object> paramsReq = new HashMap<>();
        paramsReq.put("cid", wifiRequest.getContentId());
        paramsReq.put("sid", wifiRequest.getSid());
        paramsReq.put("stime", wifiRequest.getStime());
        paramsReq.put("os", wifiRequest.getOs());
        paramsReq.put("idfa", wifiRequest.getIdfaMd5());
        paramsReq.put("mac", wifiRequest.getMacMd5());
        paramsReq.put("imei", wifiRequest.getImeiMd5());
        paramsReq.put("clientid", clientId);
        paramsReq.put("ts", System.currentTimeMillis() / 1000);
        paramsReq.put("event_type", transformType);
        //将参数转换 进行排序转换为url
        String urlParams = UrlUtil.covertParamsOrderByAsc(paramsReq);
        String finalResultUrl = accountDTO.getSspApiUrl() + "?" + urlParams;
        String sign = StringUtils.upperCase(SecureUtil.md5(finalResultUrl + accountDTO.getSspKey()));
        String resultUrl = UrlUtil.handMeitu(finalResultUrl, sign);
        log.info("账号{} 流水号{}创智如来(点淘)clientId:{}给wifi上报回传结果，完整的地址：{}", reportDTO.getDspId(), requestId,
                clientId, resultUrl);
        HttpRequest body = HttpUtil.createGet(resultUrl);
        String result = body.execute().body();
        log.info("账号{} 流水号{}创智如来(点淘)clientId:{}给wifi上报回传结果，响应的结果为{}", reportDTO.getDspId(), requestId,
                clientId, result);
        return ResponseEntity.ok(new Result());
    }





}
